library home;

import 'dart:convert';
import 'dart:io';

import 'package:app_info/app_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:smartloan_mdc/extension/extension.dart';
import 'package:smartloan_mdc/http/api/api.dart';
import 'package:smartloan_mdc/pages/dialog/version_control.dart';
import 'package:smartloan_mdc/pages/home/channel/channel_impl.dart';
import 'package:smartloan_mdc/pages/home/channel/on_back.dart';
import 'package:smartloan_mdc/pages/home/channel/timesdk_channel.dart';
import 'package:smartloan_mdc/res/string.dart';
import 'package:smartloan_mdc/utils/common/utils.dart';
import 'package:smartloan_mdc/utils/locator/app_config.dart';
import 'package:smartloan_mdc/utils/locator/locator.dart';
import 'package:smartloan_mdc/utils/storage/get_storage.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../utils/image/image_utils.dart';
import '../widgets/base_page.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart' as webview_flutter_android;

import 'channel/country_config_channel.dart';
import 'channel/liveness_channel.dart';
import 'javascript_channel.dart';

part 'home_library.dart';

class HomePage extends BasePage {
  const HomePage({super.key});

  @override
  BasePageState<BasePage> getState() => _HomePageState();
}

class _HomePageState extends BasePageState<HomePage> {

  @override
  String get pageName => 'homePage';

  double floatButtonWidth = Get.width / 11;
  Offset offsetA = Offset(0, Get.statusBarHeight + 10);
  bool dragging = false;
  bool execCheckVersion = false;
  OnBack onBackObj = OnBack();

  late WebViewController _webViewCtrl;
  late webview_flutter_android.AndroidWebViewController _androidWebViewController;
  late String url;
  late List<JavaScriptChannel> _channels;

  @override
  void initState() {
    url = Get.arguments['url'] ?? '';
    execCheckVersion = Get.arguments['checkVersion'] ?? false;
    initWebView();
    channelRegister();
    if (execCheckVersion) {
      checkNewVersion();
    }
    super.initState();
  }

  initWebView() {
    _webViewCtrl = WebViewController.fromPlatformCreationParams(
        const PlatformWebViewControllerCreationParams());

    if (Platform.isAndroid) {
      _androidWebViewController = (_webViewCtrl.platform as webview_flutter_android.AndroidWebViewController);
      _androidWebViewController.setOnShowFileSelector(_androidFilePicker);
    }

    _webViewCtrl
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
          onProgress: (int process) async {
            debugPrint('${await _webViewCtrl.currentUrl()} process: $process');
          },
          onPageFinished: (String value) {

          }
      ))
      ..enableZoom(false)
      ..addJavaScriptChannel('FKSDKJsFramework', onMessageReceived: onMessageReceive)
      ..loadRequest(Uri.parse(url));
  }

  channelRegister() {
    _channels = [
      GetLoginInfo(),
      ToAuth(),
      GetVersionName(),
      GetPackageName(),
      SetNewToken(),
      ToWhatsapp(),
      ToGooglePlayer(),
      LogEventByAF(),
      SetCountryMsg(),
      ClearCountryMsg(),
      GetAccuauthSDK(),
      TimeSdk(),
      onBackObj,
    ];
    // 适配贷超返回事件，手动注册
    onBackObj.register(_webViewCtrl, {});
  }

  @override
  Widget buildWidget() {
    return Stack(
      children: [
        SafeArea(child: WebViewWidget(
          controller: _webViewCtrl
        )),
        Positioned(
          left: offsetA.dx,
          top: offsetA.dy,
          child: refreshDrag()
        )
      ],
    );
  }

  void checkNewVersion() async {
    Map versionRes = await RequestApi.checkVersion() as Map;
    int h5VersionCode = AppStorage().readKey(StorageKey.h5Version) ?? -1;
    if (h5VersionCode < versionRes['h5VersionCode']) {
      _webViewCtrl.clearCache();
      AppStorage().writeKey(StorageKey.h5Version, versionRes['h5VersionCode']);
    }

    debugPrint('buildNumber: ${AppInfo().packageInfo!.buildNumber}');

    int netVersionCode = int.parse(versionRes['versionCode']);
    if (netVersionCode > int.parse(AppInfo().packageInfo!.buildNumber)) {
      if (!mounted) return;
      VersionDialog(force: versionRes['forcedUpdate'], onTap: () {
        Utils.toGooglePlay(versionRes['link']);
      }).show(context);
    }

  }

  void onMessageReceive(JavaScriptMessage message) async {
    debugPrint('onMessageReceive ===> ${message.message}');
    Map messageMap = jsonDecode(message.message);

    for (var element in _channels) {
      if (element.actions.contains(messageMap['action'])) {
        if (element.webCtrl == null) {
          await element.register(_webViewCtrl, messageMap);
        }
        element.onReceive(messageMap);
      }
    }

  }

  @override
  Future<bool> onWillPop() async {
    return onBackObj.onBack(url);
  }

  Widget refreshDrag() {
    return SafeArea(
        child: Draggable(
          child: dragging ? SizedBox() : floatButton(),
          feedback: floatButton(),
          onDragStarted: (){
            setState(() {
              dragging = true;
            });
          },
          onDragEnd: (DraggableDetails details) {
            setState(() {
              dragging = false;
            });
          },
          onDraggableCanceled:
              (Velocity velocity, Offset offset) {

            // 计算组件可移动范围  更新位置信息
            setState(() {
              var x = offset.dx;
              var y = offset.dy;

              if (x < Get.width / 2) {
                x = 0;
              } else {
                x = Get.width - floatButtonWidth;
              }

              if (y < 20) {
                y = 20;
              }
              if (y > Get.height - Get.statusBarHeight - floatButtonWidth) {
                y = Get.height - Get.statusBarHeight - floatButtonWidth;
              }

              offsetA = Offset(x, y);

            });
          },
        )
    );
  }

  Widget floatButton() {
    return SizedBox(
      width: floatButtonWidth,
      height: floatButtonWidth,
      child: FloatingActionButton(
        tooltip: 'Increment',
        backgroundColor: Colors.black.withOpacity(0.2),
        onPressed: () async {
          await _webViewCtrl.clearCache();
          _webViewCtrl.loadRequest(Uri.parse(locator<AppConfig>().appConfigModel.baseUrl ?? ''));
        },
        child: const Icon(
          Icons.refresh,
          color: Colors.white,
        ),
      ),
    );
  }

}